import { defineComponent, onMounted, type PropType, reactive, ref, toRefs } from 'vue'
import {
  Button,
  Card,
  Checkbox,
  CheckboxGroup,
  Col,
  Form,
  FormItem,
  Input,
  Radio,
  RadioGroup,
  Row,
  Textarea
} from 'ant-design-vue'
import { useDetail } from './use-detail'
import { useForm } from './use-form'
import { BusinessPageTypeEnum } from '@/enums/pageTypeEnum'
import _ from 'lodash-es'

const RoleDetail = defineComponent({
  name: 'RoleDetail',
  props: {
    code: {
      type: [String, Number],
      required: false
    },
    businessType: {
      type: String as PropType<BusinessPageTypeEnum>,
      required: true,
      validator: (value: string) => {
        // 检查传入的值是否在枚举的有效值中
        return Object.values(BusinessPageTypeEnum).includes(value as BusinessPageTypeEnum)
      }
    }
  },
  emits: ['cancelModal', 'confirmModal'],
  setup(props, ctx) {
    const { meta, state, initForm, getFormValues } = useForm()
    const { status, createOrUpdate, getRoleById, getMenuList, getMenuListByRoleById, getDataPermissionOptions } =
      useDetail(getFormValues)
    const checkAllState = reactive({
      checkAll: false,
      selectedPermissions: {},
      indeterminateStates: {},
      menuList: [] as any[]
    })
    const dataPermissionList = ref<any>([])
    const handleCommit = async () => {
      const menuIds = [] as any[]
      Object.keys(checkAllState.selectedPermissions).forEach((key: any) => {
        if (checkAllState.selectedPermissions[key]) {
          Object.keys(checkAllState.selectedPermissions[key]).forEach((key1: any) => {
            menuIds.push(key)
            menuIds.push(key1)
            if (checkAllState.selectedPermissions[key][key1].length > 0) {
              checkAllState.selectedPermissions[key][key1].forEach((item: any) => {
                menuIds.push(item)
              })
            }
          })
        }
      })
      // 计算数据权限
      const dataPermissionData = [] as any[]
      dataPermissionList.value.forEach((item: any) => {
        item.dataPermissionBOList.forEach(item1 => {
          if (item1.dataPermission === 1 || item1.dataPermission === 2) {
            dataPermissionData.push(item1)
          }
        })
      })
      state.detailForm.menuCodes = [...new Set(menuIds)]
      state.detailForm.dataPermissionDataList = dataPermissionData
      await createOrUpdate()
      initForm()
      ctx.emit('confirmModal')
    }

    const resetForm = () => {
      initForm()
      ctx.emit('cancelModal')
    }

    const onCheckAllChange = (e: any) => {
      checkAllState.checkAll = e.target.checked
      checkAllState.menuList.forEach((catalog: any) => {
        catalog.menuList.forEach((menu: any) => {
          checkAllState.selectedPermissions[catalog.menuId][menu.menuId] = e.target.checked
            ? menu.buttonList.map((btn: any) => btn.menuId)
            : []
          checkAllState.indeterminateStates[menu.menuId] = false
        })
      })
    }

    // 单个菜单的全选与取消操作，控制 button 的选中状态
    const handleMenuChange = (fMenuId: number, menu: any, checked: boolean) => {
      checkAllState.selectedPermissions[fMenuId][menu.menuId] = checked
        ? menu.buttonList.map((btn: any) => btn.menuId)
        : []
      // 更新全选状态
      checkAllState.indeterminateStates[menu.menuId] = false
      updateSelectAllState()
    }

    // 更新 menuName 的状态，当所有 buttonName 选中时，menuName 选中
    const updateMenuState = (fMenuId: number, menuId: number) => {
      const menu = checkAllState.menuList
        .flatMap((catalog: any) => catalog.menuList)
        .find((m: any) => m.menuId === menuId)
      const allChecked = checkAllState.selectedPermissions[fMenuId][menuId].length === menu.buttonList.length
      checkAllState.indeterminateStates[menu.menuId] =
        checkAllState.selectedPermissions[fMenuId][menuId].length > 0 && !allChecked // 设置半满状态
      // 更新 menu 的 checkbox 状态
      if (allChecked) {
        checkAllState.selectedPermissions[fMenuId][menu.menuId] = menu.buttonList.map((btn: any) => btn.menuId)
      }
    }

    // 更新全选按钮状态
    const updateSelectAllState = () => {
      checkAllState.checkAll = checkAllState.menuList.every((catalog: any) =>
        catalog.menuList.every(
          (menu: any) =>
            checkAllState.selectedPermissions[catalog.menuId][menu.menuId].length === menu.buttonList.length
        )
      )
    }

    // 单项选择功能
    const handleGroupChange = (fMenuId: number, menuId: number, checkedValues: string[]) => {
      checkAllState.selectedPermissions[fMenuId][menuId] = checkedValues
      // 更新 menuName 的选中状态以及全选状态
      updateMenuState(fMenuId, menuId)
      updateSelectAllState()
    }

    const fetchMenuList = async (menuIdsList: any[]) => {
      const menuDataList = await getMenuList()
      checkAllState.menuList = menuDataList
      menuDataList &&
        menuDataList.forEach((catalog: any) => {
          checkAllState.selectedPermissions[catalog.menuId] = {}
          catalog.menuList.forEach((menu: any) => {
            checkAllState.selectedPermissions[catalog.menuId][menu.menuId] = []
            checkAllState.indeterminateStates[menu.menuId] = false
            // 判断是否已经有选中的了，加进去
            if (menuIdsList != null && menuIdsList.length > 0) {
              // 判断是否选中，获取所有选中的id
              const buttonIdList = menu.buttonList.map((btn: any) => btn.menuId)
              // 求交集
              const intersection = _.intersection(menuIdsList, buttonIdList)
              if (intersection != null && intersection.length > 0) {
                checkAllState.selectedPermissions[catalog.menuId][menu.menuId] = intersection
              }
            }
          })
        })
      updateSelectAllState()
    }

    const fetchDataPermissionList = async (roleDataPermissionList: any[]) => {
      const map = new Map()
      roleDataPermissionList.forEach(item => {
        const key = `${item.menuCode}-${item.dataPermissionCode}`
        map.set(key, item.dataPermission)
      })
      const allDataPermissionList = await getDataPermissionOptions()
      allDataPermissionList.forEach(item => {
        item.dataPermissionBOList.forEach(item1 => {
          const key = `${item1.menuCode}-${item1.dataPermissionCode}`
          if (map.has(key)) {
            item1.dataPermission = map.get(key)
          }
        })
      })
      dataPermissionList.value = allDataPermissionList
      console.log(dataPermissionList)
    }

    const fetchData = async () => {
      if (props.businessType === BusinessPageTypeEnum.UPDATE || props.businessType === BusinessPageTypeEnum.DETAIL) {
        // 查询值
        state.detailForm = await getRoleById(props.code)
        state.detailForm.menuCodes = await getMenuListByRoleById(props.code)
      }
      // 组合选中的值
      await fetchMenuList(state.detailForm.menuCodes)
      await fetchDataPermissionList(state.detailForm.dataPermissionDataList)
    }

    onMounted(async () => {
      await fetchData()
    })

    return {
      ...toRefs(props),
      ...toRefs(state),
      ...toRefs(status),
      ...toRefs(meta),
      checkAllState,
      dataPermissionList,
      onCheckAllChange,
      handleGroupChange,
      handleMenuChange,
      handleCommit,
      resetForm
    }
  },

  render() {
    const {
      businessType,
      detailForm,
      rules,
      checkAllState,
      dataPermissionList,
      onCheckAllChange,
      handleGroupChange,
      handleMenuChange,
      handleCommit,
      resetForm
    } = this
    return (
      <>
        <span>{businessType}</span>
        <Card>
          <Form
            ref='detailFormRef'
            model={detailForm}
            rules={rules}
            labelCol={{ span: 2 }}
            wrapperCol={{ span: 18 }}
            style={{ width: '80%' }}
            onFinish={handleCommit}
          >
            <FormItem label='角色名' name='name'>
              <Input
                disabled={businessType === BusinessPageTypeEnum.DETAIL}
                v-model={[detailForm.name, 'value']}
                showCount
                maxlength={30}
                placeholder='请输入内容'
              />
            </FormItem>

            <FormItem label='描述' name='description'>
              <Textarea
                disabled={businessType === BusinessPageTypeEnum.DETAIL}
                v-model={[detailForm.description, 'value']}
                maxlength={200}
                rows={3}
                placeholder='请输入内容'
              />
            </FormItem>
            <FormItem label='操作权限' name='description'>
              <Row>
                <Col>
                  <Checkbox
                    disabled={businessType === BusinessPageTypeEnum.DETAIL}
                    v-model:checked={checkAllState.checkAll}
                    indeterminate={
                      !checkAllState.checkAll && Object.values(checkAllState.indeterminateStates).some(Boolean)
                    }
                    onChange={onCheckAllChange}
                  >
                    全选
                  </Checkbox>
                </Col>
              </Row>
              {checkAllState.menuList &&
                checkAllState.menuList.map(item => {
                  return (
                    <>
                      <div style={{ marginBottom: '10px', marginTop: '10px', fontWeight: 'bold' }}>
                        {item.catalogName}
                      </div>
                      {item.menuList &&
                        item.menuList.map(mItem => {
                          return (
                            <Row>
                              <Col span={6}>
                                <Checkbox
                                  disabled={businessType === BusinessPageTypeEnum.DETAIL}
                                  indeterminate={checkAllState.indeterminateStates[mItem.menuId]}
                                  checked={
                                    checkAllState.selectedPermissions[item.menuId][mItem.menuId].length ===
                                    mItem.buttonList.length
                                  }
                                  onChange={e => handleMenuChange(item.menuId, mItem, e.target.checked)}
                                >
                                  {mItem.menuName}
                                </Checkbox>
                              </Col>
                              <Col span={18}>
                                <CheckboxGroup
                                  disabled={businessType === BusinessPageTypeEnum.DETAIL}
                                  value={checkAllState.selectedPermissions[item.menuId][mItem.menuId]}
                                  onChange={checkedValues =>
                                    handleGroupChange(item.menuId, mItem.menuId, checkedValues)
                                  }
                                >
                                  {mItem.buttonList &&
                                    mItem.buttonList.map(item1 => {
                                      return (
                                        <Checkbox
                                          disabled={businessType === BusinessPageTypeEnum.DETAIL}
                                          value={item1.menuId}
                                        >
                                          {item1.buttonName}
                                        </Checkbox>
                                      )
                                    })}
                                </CheckboxGroup>
                              </Col>
                            </Row>
                          )
                        })}
                    </>
                  )
                })}
            </FormItem>
            <FormItem label='数据权限' name='description'>
              {dataPermissionList &&
                dataPermissionList.map(catalog => (
                  <div key={catalog.catalogName}>
                    <div style={{ marginBottom: '10px', marginTop: '10px', fontWeight: 'bold' }}>
                      {catalog.catalogName}
                    </div>
                    {catalog.dataPermissionBOList.map(menu => (
                      <Row gutter={12}>
                        <Col span={6}>
                          <span>{menu.menuName}</span>
                        </Col>
                        <Col span={6}>
                          <RadioGroup
                            v-model={[menu.dataPermission, 'value']}
                            disabled={businessType === BusinessPageTypeEnum.DETAIL}
                          >
                            <Radio value={1}>全部</Radio>
                            <Radio value={2}>只自己</Radio>
                          </RadioGroup>
                        </Col>
                      </Row>
                    ))}
                  </div>
                ))}
            </FormItem>
            <FormItem wrapperCol={{ span: 12, offset: 12 }}>
              {businessType === BusinessPageTypeEnum.DETAIL && <Button onClick={resetForm}>返回</Button>}
              {businessType !== BusinessPageTypeEnum.DETAIL && (
                <>
                  <Button type='primary' htmlType='submit'>
                    提交
                  </Button>
                  <Button style={{ marginLeft: '12px' }} onClick={resetForm}>
                    取消
                  </Button>
                </>
              )}
            </FormItem>
          </Form>
        </Card>
      </>
    )
  }
})
export default RoleDetail
